<template>
  <header class="w-10 font-size-9">
    <el-row class="bg-gray p-1" justify="center">
      <el-col :span="14" :offset="10">   <!-- 头部导航 -->
        <router-link to="/login" class="px-1" >你好，{{ data.token?data.username:"请登录" }}</router-link>
        <router-link to="/regiest" class="px-1" v-if="!data.token">免费注册</router-link>
        <el-divider direction="vertical" />
        <template v-for="(item,index) in data.nav" :key="index">
          <router-link :to="item.path" class="px-1" >{{ item.title }}</router-link>
          <el-divider direction="vertical" />
        </template>
        <router-link to="/login" class="px-2" v-if="data.token" @click="logout">安全退出</router-link>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="4" class="p-1">    <!-- logo -->
        <img src="../assets/images/logo7.png" class="w-80">
      </el-col>
      <el-col :span="18" :offset="2">
        <el-row>
          <el-col :span="18" class="my-4">
            <Search></Search>   <!-- 搜索子组件-->
          </el-col>    <!-- 购物车 -->
          <el-col :span="5" :offset="1" class="my-4">
            <el-button class="red h-40" :icon="ShoppingCart" @click="toCart">我的购物车</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">          <!-- 公司分类导航 -->
            <template v-for="(item,index) in data.company" :key="index">
              <router-link :to="'/list?cname='+item.name" class="px-1">{{ item.name }}</router-link>
              <el-divider direction="vertical" v-if="index!=data.company.length-1" />
            </template>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </header>
</template>

<script setup>
import Search from "@/components/Search.vue"
import { ShoppingCart } from '@element-plus/icons-vue'
import { reactive,onMounted,getCurrentInstance,computed } from 'vue'
import { useRouter } from 'vue-router'
const { proxy } = getCurrentInstance()  //获取当前实例的代理对象proxy
const data = reactive({
  nav:[],
  company:[],
  username:'',
  token:false
})

let getCompany = ()=>{          //公司数据
  proxy.$http({                 //通过代理对象取得在main.js挂载全局对象axios
    method:"get",               //设置网络请求方式为get，默认方式，可以省略
    url:"./data/company.json"
  }).then(res=>{
    data.company = res.data
  })
  console.log(data.company)
}
//得到头部导航
let getNav = ()=>{          
  proxy.$http({                 
    method:"get",               
    url:"./data/header-nav.json"
  }).then(res=>{
    data.nav = res.data
  })
}

let getToken=()=>{
  data.token = sessionStorage.getItem("token")
  if(data.token) {
    data.username =localStorage.getItem("username")
  }
}

let logout=()=>{
  sessionStorage.clear()
}

const router = useRouter()
const toCart = ()=>{
  router.push({path:"/cart"})
}

onMounted(()=>{
  getNav()                //获取导航数据 
  getCompany()            //获取公司数据 
  getToken()              //获取用户登录信息
})
</script>

<style scoped>
</style>